package com.guaju.yueshangLife.net;


import android.content.pm.PackageManager;
import android.text.TextUtils;

import com.google.gson.GsonBuilder;
import com.guaju.yueshangLife.constant.ConstanceValue;
import com.guaju.yueshangLife.global.BaseApplication;
import com.guaju.yueshangLife.utils.PreferenceUtil;
import com.guaju.yueshangLife.utils.Utils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;


/**
 *
 */
public class ApiClient {

    public static void setInstance(ApiClient instance) {
        ApiClient.instance = instance;
    }

    private volatile static ApiClient instance;

    private ApiClient(){}

    public static synchronized ApiClient getInstance(){
        if(instance==null){
            synchronized(ApiClient.class){
                if(instance==null)
                    instance=new ApiClient();
            }
        }
        return instance;
    }

    private static Retrofit mRetrofit;
    private static Retrofit mRetrofit1;

    private OkHttpClient initRetrofit(){
        // 指定缓存路径,缓存大小100Mb
        Cache cache = new Cache(new File(BaseApplication.getInstance().getCacheDir(), "yslife"),
                1024 * 1024 * 100);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (ConstanceValue.DH_DEBUG) {
            // Log信息拦截器
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            //设置 Debug Log 模式
            builder.addInterceptor(loggingInterceptor);
        }
        Interceptor cacheInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!NetworkUtil.isConnected(BaseApplication.getInstance())) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }
                Response response = chain.proceed(request);
                if (NetworkUtil.isConnected(BaseApplication.getInstance())) {
                    int maxAge = 0;
                    // 有网络时 设置缓存超时时间0个小时
                    response.newBuilder()
                            .header("Cache-Control", "public, max-age=" + maxAge)
                            .removeHeader("DHTopNews")
                            .build();
                } else {
                    // 无网络时，设置超时为1周
                    int maxStale = 60 * 60 * 24 * 7;
                    response.newBuilder()
                            .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                            .removeHeader("nyn")
                            .build();
                }
                return response;
            }
        };
        builder.cache(cache).addInterceptor(cacheInterceptor);

        //设置超时
        builder.connectTimeout(10, TimeUnit.SECONDS);
        builder.readTimeout(15, TimeUnit.SECONDS);
        builder.writeTimeout(15, TimeUnit.SECONDS);
        //错误重连
        builder.retryOnConnectionFailure(true);

        builder.addInterceptor(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request.Builder builder = chain.request().newBuilder();
                builder.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.108 Safari/537.36 2345Explorer/8.0.0.13547");
                builder.addHeader("accept", "application/json");
                builder.addHeader("Upgrade-Insecure-Requests", "1");
                builder.addHeader("X-Requested-With", "XMLHttpRequest");
                builder.addHeader("DeviceToken", "");
                if (PreferenceUtil.getIsLogin()){
                    builder.addHeader("UserToken", PreferenceUtil.getToken());
                    builder.addHeader("UserId", PreferenceUtil.getUserId()+"");
                }
                try {
                    builder.addHeader("Vercode", BaseApplication.getInstance().getPackageManager().getPackageInfo(BaseApplication.getInstance().getPackageName(),0).versionCode +"");
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
//                builder.addHeader("Vercode", "10021"); // 百度单独版本号
                builder.addHeader("DeviceUniqid", Utils.getDeviceId(BaseApplication.getInstance()));
                builder.addHeader("AppInfo", getAppInfo(BaseApplication.getInstance()));
                builder.addHeader("AndroidId", Utils.getUniquePsuedoID());
//                builder.addHeader("MacAddress", Utils.getAppMac());
                if (!TextUtils.isEmpty(PreferenceUtil.getToken())){
                builder.addHeader("Authorization", "Bearer "+PreferenceUtil.getToken());
                }
                return chain.proceed(builder.build());
            }
        });

        OkHttpClient okHttpClient = builder.build();
        return okHttpClient;
    }

    /**
     * @return
     */
    public Retrofit retrofit() {
        if (mRetrofit == null) {
            OkHttpClient okHttpClient = initRetrofit();
            mRetrofit = new Retrofit.Builder()
                    .baseUrl(ApiService.API_SERVER_URL)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(okHttpClient)
                    .build();
        }
        return mRetrofit;
    }
    public Retrofit retrofit1() {
        if (mRetrofit1 == null) {
            OkHttpClient okHttpClient = initRetrofit();
            mRetrofit1 = new Retrofit.Builder()
                    .baseUrl(ApiService.API_SERVER_URL1)
                    .addConverterFactory(ScalarsConverterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().create()))
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .client(okHttpClient)
                    .build();
        }
        return mRetrofit1;
    }

    public ApiService getApiService() {
        return retrofit().create(ApiService.class);
    }

    public ApiService getApiService1() {
        return retrofit1().create(ApiService.class);
    }

    public String getAppInfo(BaseApplication appContext) {
        StringBuilder ua = new StringBuilder();
        String packageName = appContext.getPackageName();
        try {
            ua.append(appContext.getPackageManager().getPackageInfo(packageName,0).versionName);// app版本信息
            ua.append("/" + appContext.getPackageManager().getPackageInfo(packageName,0).versionCode);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        ua.append("/Android");// 手机系统平台
        ua.append("/" + android.os.Build.VERSION.RELEASE);// 手机系统版本
        ua.append("/" + android.os.Build.MODEL); // 手机型号
        ua.append("/" + Utils.getDeviceId(appContext));// 客户端唯一标识
//        ua.append("/" + Utils.readMetaDataIntStr(appContext,"UMENG_CHANNEL_VALUE"));// 客户端渠道号
        return ua.toString();
    }

    public static void release(){
        instance=null;
    }


}
